#include "QComboBoxSearch.h"
#include "ui_QComboBoxSearch.h"

#include <QKeyEvent>

QComboBoxSearch::QComboBoxSearch(QWidget *parent) :
    QComboBox(parent),
    ui(new Ui::QComboBoxSearch)
{
    ui->setupUi(this);
    //允许编辑text作为搜索
    this->setEditable(true);
    // 获取当前模型
    QStringListModel *sourceModel = new QStringListModel(this);
    this->setModel(sourceModel);

    // 创建过滤模型
    filterModel = new QSortFilterProxyModel(this);
    filterModel->setSourceModel(sourceModel);
    filterModel->setFilterRole(Qt::DisplayRole);
    // 设置自定义完成器
    completer = new QCompleter(filterModel, this);
    completer->setCompletionMode(QCompleter::PopupCompletion);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    completer->setFilterMode(Qt::MatchContains);
    this->setCompleter(completer);

    // 当用户按下Enter或失去焦点时，检查输入是否匹配现有选项

}

QComboBoxSearch::~QComboBoxSearch()
{
    delete ui;
}


void QComboBoxSearch::keyPressEvent(QKeyEvent *event)
{
    // 处理Enter/Return键
    if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
        // 自定义Enter键逻辑
        // 当编辑完成时，检查输入是否匹配某个选项
        bool found = false;

        for (int i = 0; i < this->count(); i++) {
            if (this->itemText(i) == this->currentText()) {
                this->setCurrentIndex(i);
                found = true;
                break;
            }
        }

        // 如果没有找到匹配项，可以选择清空或保留输入
        if (!found) {
            // 这里选择保留输入，你也可以选择清空：setCurrentText("");
            this->setCurrentText("");
        }

        event->accept();  // 接受事件，不再继续处理
        return;
    }

    // 其他按键交给基类处理
    QComboBox::keyPressEvent(event);

}

void QComboBoxSearch::on_ui_box_editTextChanged(const QString &text)
{
    // 更新过滤模型
    filterModel->setFilterFixedString(text);
    filterModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
//    // 输入中显示匹配的选项卡
//    this->showPopup();


}

